#
# "@(#) $Id: utils.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
import fcntl, os, re, select

def unikode(s):
	if type(s).__name__=='unicode': return s
	try: return unicode(s)
	except: pass
	try: return unicode(s,'latin-1')
	except: pass
	try: return unicode(s,'utf-8')
	except: pass
	return s

def readlinex(fh,buffer):
	try:
		i = buffer.index('\n')
		if i>=0:
			i = i+1
			line = buffer[:i]
			buffer = buffer[i:]
			return (line,buffer)
	except: pass
	fd = fh.fileno()
	while 1:
		#print "waiting on select"
		ready = select.select([fd],[],[])
		#print "ready",ready
		if fd in ready[0]:
			chunk = fh.read()
			#print "got data",chunk
			if chunk=='': return (None,None)
			chunk = re.sub('\r','\n',chunk)
			buffer = buffer+chunk
			try:
				i = buffer.index('\n')
				if i>=0:
					i = i+1
					line = buffer[:i]
					buffer = buffer[i:]
					return (line,buffer)
			except: pass
		try: select.select([],[],[],0.1)
		except: pass

def makeNonBlocking(fd):
	fl = fcntl.fcntl(fd,fcntl.F_GETFL)
	try:
		fcntl.fcntl(fd,fcntl.F_SETFL,fl | os.O_NDELAY)
	except AttributeError:
		fcntl.fcntl(fd,fcntl.F_SETFL,fl | fcntl.FNDELAY)

def lock(file,flags = fcntl.LOCK_EX):
	fcntl.flock(file.fileno(),flags)

def unlock(file):
	fcntl.flock(file.fileno(),fcntl.LOCK_UN)
